package com.wh.wisdomsite.xbox.server;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.ba.entity.AppSecret;
import com.wh.wisdomsite.xbox.ba.service.IAppSecretService;
import com.wh.wisdomsite.xbox.pojo.ba.AppSecretIn;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.core.ServiceDispatcher;
import com.wh.wisdomsite.xbox.server.manager.SampleInvokeTimesController;
import com.wh.wisdomsite.xbox.utils.date.DateTool;
import com.wh.wisdomsite.xbox.utils.encrypt.md5.MD5Tool_Two;
import com.wh.wisdomsite.xbox.server.manager.SampleAppSecretManager;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

/**
 * 密钥管理控制器Controller
 * @Package com.wh.wisdomsite.xbox.server
 * @author 谢泽鹏
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2014
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/appSecret")
public class AppSecretController {

    private static final Log logger = LogFactory.getLog(AppSecretController.class);

    @Resource(name = "serviceDispatcher")
    private ServiceDispatcher serviceDispatcher;

    @Autowired
    private IAppSecretService iAppSecretService;


    /**
     * 跳转到秘钥列表页面
     * @return
     */
    @RequiresPermissions("rules:dataServices_appSecret_page")
    @RequestMapping("index.do")
    public String index(){
        return "/dataServices/appSecret/appSecretList";
    }


    /**
     * 加载秘钥列表信息
     * @param response
     */
    @RequiresPermissions("rules:dataServices_appSecret_ref")
    @RequestMapping(value = "/findPage.do", method = RequestMethod.POST)
    public void findPage(HttpServletResponse response, AppSecretIn in) {
        JSONObject json = new JSONObject();
        try {
            logger.info("秘钥列表-->>开始");
            //设置默认分页参数 页码：1 条数：10
            if(in.getPage() == 0) in.setPage(1);
            if(in.getRows() == 0) in.setRows(10);
            //设置分页
            Page<AppSecret> page = new Page<AppSecret>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<AppSecret> ewAppSecret = new EntityWrapper<AppSecret>();
            ewAppSecret.setEntity(new AppSecret());
            ewAppSecret.orderBy("T_CREATE_DATE", false);
            JSONArray array = new JSONArray();
            Page<AppSecret> pageAppSecret = iAppSecretService.selectPage(page, ewAppSecret);
            if(null != pageAppSecret.getRecords() && pageAppSecret.getRecords().size() > 0){
                for(AppSecret appSecret : pageAppSecret.getRecords()){
                    JSONObject object = new JSONObject(appSecret);
                    object.put("id", appSecret.getId());
                    object.put("createDate", DateTool.format(appSecret.getCreateDate(),"yyyy-MM-dd HH:mm:ss"));
                    object.put("updateDate", DateTool.format(appSecret.getUpdateDate(),"yyyy-MM-dd HH:mm:ss"));
                    array.put(object);
                }
            }
            json.put("total", pageAppSecret.getTotal());
            json.put("rows", array);
            ResManager.getJsonOut(response).print(json);
        } catch (Exception e){
            e.printStackTrace();
            logger.error("秘钥列表-->>Exception" + e.getMessage());
            ResManager.getJsonOut(response).print(json);
        }
            logger.info("秘钥列表-->>结束");
    }



    /**
     * 秘钥详情
     * @param appSecretIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:dataServices_appSecret_view")
    @RequestMapping("appSecretDesc.do")
    public String appSecretDesc(AppSecretIn appSecretIn, HttpServletRequest request) {
        AppSecret appSecret = iAppSecretService.selectById(appSecretIn.getId());
        request.setAttribute("appSecret", appSecret);
        request.setAttribute("createDate", DateTool.format(appSecret.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
        request.setAttribute("updateDate", DateTool.format(appSecret.getUpdateDate(), "yyyy-MM-dd HH:mm:ss"));
        return "/dataServices/appSecret/appSecretDesc";
    }


    /**
     * 操作秘钥(添加/修改)
     * @param appSecret
     * @param response
     * @throws Exception
     */
    @RequiresPermissions("rules:dataServices_appSecret_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(AppSecret appSecret, HttpServletResponse response){
        try {
            //判断方法是否已经存在,存在即更新.否则为添加
            if(StringUtils.isNotEmpty(appSecret.getId())){
                logger.info("修改秘钥-->>开始");
                appSecret.setUpdateDate(new Date());
                appSecret.setSecret(MD5Tool_Two.MD5(appSecret.getSecret()));
                iAppSecretService.updateById(appSecret);
                logger.info("修改秘钥-->>结束");
                ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("秘钥更新成功"));
            }else {
                logger.info("添加秘钥-->>开始");
                appSecret.setCreateDate(new Date());
                appSecret.setSecret(MD5Tool_Two.MD5(appSecret.getSecret()));
                appSecret.setId(UUID.randomUUID().toString().replace("-",""));
                iAppSecretService.insert(appSecret);
                logger.info("添加秘钥-->>结束");
                ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("秘钥添加成功"));
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("操作秘钥-->>Exception" + e.getMessage());
        }
    }


    /**
     * 删除秘钥
     * @param id
     * @param response
     */
    @RequiresPermissions("rules:dataServices_appSecret_del")
    @RequestMapping(value = "/del.do", method = RequestMethod.GET)
    public void del(String id, HttpServletResponse response){
        try{
            logger.info("删除秘钥-->>开始");
            iAppSecretService.deleteById(id);
            logger.info("删除秘钥-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("秘钥删除成功"));
        } catch (Exception e){
            e.printStackTrace();
            logger.error("删除秘钥-->>Exception" + e.getMessage());
        }
    }


    /**
     * 重置应用密钥
     * @param response
     */
    @RequiresPermissions("rules:dataServices_appSecret_reset")
    @RequestMapping(value = "/restAppKeySecret.do", method = RequestMethod.GET)
    public void setAppKeySecret(HttpServletResponse response) {
        try {
            logger.info("重置应用密钥-->>开始");
            Map<String, String> appAppKeySecretMap = new HashMap<String, String>();
            EntityWrapper<AppSecret> ew = new EntityWrapper<AppSecret>();
            ew.setEntity(new AppSecret());
            List<AppSecret> appSecretList = iAppSecretService.selectList(ew);
            for (AppSecret appSecret : appSecretList) {
                appAppKeySecretMap.put(appSecret.getAppKey(), appSecret.getSecret());
            }
            ((SampleAppSecretManager) serviceDispatcher.getSecurityManager().getAppSecretManager()).setAppKeySecretMap(appAppKeySecretMap);
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("重置应用密钥成功"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("重置应用密钥-->>Exception" + e.getMessage());
        }
            logger.info("重置应用密钥-->>结束");
    }

    /**
     * 计数器清零
     * @param appKey
     * @param response
     */
    @RequiresPermissions("rules:dataServices_appSecret_clear")
    @RequestMapping(value = "/resetAppCallAllCount.do", method = RequestMethod.GET)
    public void resetAppCallAllCount(String appKey, HttpServletResponse response){
        try {
            logger.info("计数器清零-->>开始");
            SampleInvokeTimesController.resetAppCallCounter(appKey);
            logger.info("计数器清零-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("记数器清零成功"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("计数器清零-->>Exception" + e.getMessage());
        }
    }


    /**
     * 跳转至页面
     * @return
     */
    @RequestMapping("/toAppSecret")
    public ModelAndView toAddActivity(){
        return new ModelAndView("dataServices/appSecret/appSecretOption");
    }



}
